import _ from "lodash";
import { isObject } from "./object.js";


/**
 * 移除含有空name对象的元素
 * @param {Array} list
 * @param {Function|String} condition
 * @returns {*}
 */
export const removeEmptyNameItem = function (
  list,
  condition
) {
  const handleObject = function (obj) {
    if (!isObject(obj)) {
      return;
    }
    for (let key in obj) {
      if (Array.isArray(obj[key])) {
        remove(obj[key]);
      }
    }
  };

  const handleArray = function (list) {
    if (!Array.isArray(list)) {
      return;
    }
    for (let i = list.length - 1; i >= 0; i--) {
      const item = list[i];
      if (!isObject(item)) {
        continue;
      }

      // 条件字符串时，当前属性名判断是否为空字符串
      if (typeof condition === "string") {
        if (String(item[condition]).length === 0) {
          list.splice(i, 1);
          continue;
        }
      }

      // 使用回调函数返回true删除
      if (typeof condition === "function") {
        if (condition(item)) {
          list.splice(i, 1);
          continue;
        }
      }

      remove(item);
    }
  };

  const remove = function (data) {
    handleObject(data);
    handleArray(data);

    return data;
  };

  // 深度复制避免修改输入参数
  return remove(_.cloneDeep(list));
};
